<template>
  <div class="chat-page">
    <h1>在线咨询</h1>
    
    <div class="chat-container">
      <div class="chat-header">
        <h2>客服聊天</h2>
        <div class="connection-status" :class="connectionStatus">
          {{ connectionStatusText }}
        </div>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message', message.sender ? message.sender.toLowerCase() : 'system']"
        >
          <div class="message-content">
            <div class="sender">{{ getMessageSenderName(message.sender) }}</div>
            <div class="content">{{ message.content }}</div>
            <div class="timestamp">{{ formatTimestamp(message.timestamp) }}</div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <input 
          v-model="newMessage" 
          @keyup.enter="sendMessage" 
          placeholder="输入消息..." 
          :disabled="!isConnected"
        />
        <button @click="sendMessage" :disabled="!isConnected || !newMessage.trim()">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client'

export default {
  name: 'ChatView',
  data() {
    return {
      stompClient: null,
      isConnected: false,
      messages: [],
      newMessage: '',
      sessionId: this.generateSessionId()
    }
  },
  computed: {
    connectionStatus() {
      return this.isConnected ? 'connected' : 'disconnected'
    },
    connectionStatusText() {
      return this.isConnected ? '已连接' : '未连接'
    }
  },
  mounted() {
    this.connect()
  },
  beforeUnmount() {
    this.disconnect()
  },
  methods: {
    connect() {
      try {
        // 创建SockJS连接
        const socket = new SockJS('http://localhost:8080/websocket')
        
        // 创建STOMP客户端
        this.stompClient = new Client({
          webSocketFactory: () => socket,
          connectHeaders: {},
          debug: function (str) {
            console.log(str)
          },
          reconnectDelay: 5000,
          heartbeatIncoming: 4000,
          heartbeatOutgoing: 4000,
        })

        // 连接回调
        this.stompClient.onConnect = (frame) => {
          console.log('Connected: ' + frame)
          this.isConnected = true
          this.sendSystemMessage('连接已建立')
          
          // 订阅公共消息频道
          this.stompClient.subscribe('/topic/messages', (message) => {
            this.handleReceivedMessage(message)
          })
          
          // 订阅用户特定消息频道
          this.stompClient.subscribe('/user/queue/messages', (message) => {
            this.handleReceivedMessage(message)
          })
        }

        // 错误回调
        this.stompClient.onStompError = (frame) => {
          console.log('Broker reported error: ' + frame.headers['message'])
          console.log('Additional details: ' + frame.body)
          this.sendSystemMessage('连接出现错误: ' + frame.headers['message'])
        }
        
        this.stompClient.onWebSocketError = (error) => {
          console.log('WebSocket error: ', error)
          this.sendSystemMessage('WebSocket连接错误: ' + error.message)
        }
        
        this.stompClient.onDisconnect = () => {
          console.log('Disconnected')
          this.isConnected = false
          this.sendSystemMessage('连接已断开')
        }

        // 激活连接
        this.stompClient.activate()
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        this.sendSystemMessage('连接服务暂时不可用: ' + error.message)
      }
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.deactivate()
        this.isConnected = false
        console.log("Disconnected")
      }
    },
    sendMessage() {
      if (this.newMessage.trim() && this.stompClient && this.stompClient.active) {
        const chatMessage = {
          sender: 'USER',
          content: this.newMessage,
          sessionId: this.sessionId,
          status: 'SENT'
        }
        
        try {
          // 通过STOMP发送消息到后端
          this.stompClient.publish({
            destination: "/app/chat",
            body: JSON.stringify(chatMessage)
          })
          
          // 用户消息不在这里显示，等待后端回显以避免重复
          
          // 清空输入框
          this.newMessage = ''
        } catch (error) {
          console.error('发送消息失败:', error)
          this.sendSystemMessage('消息发送失败: ' + error.message)
        }
      }
    },
    handleReceivedMessage(message) {
      try {
        console.log('收到原始消息:', message)
        console.log('消息体:', message.body)
        const parsedMessage = JSON.parse(message.body)
        console.log('解析后的消息:', parsedMessage)
        this.showMessage(parsedMessage)
      } catch (e) {
        console.error('解析消息失败:', e)
        console.error('原始消息体:', message.body)
        this.sendSystemMessage('解析消息失败: ' + e.message)
      }
    },
    showMessage(message) {
      this.messages.push(message)
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    sendSystemMessage(content) {
      const systemMessage = {
        sender: 'SYSTEM',
        content: content,
        sessionId: this.sessionId,
        status: 'DELIVERED',
        timestamp: new Date().toISOString()
      }
      this.showMessage(systemMessage)
    },
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    generateSessionId() {
      return 'session_' + Math.random().toString(36).substr(2, 9)
    },
    getMessageSenderName(sender) {
      switch (sender) {
        case 'USER': return '您'
        case 'AGENT': return '客服'
        case 'SYSTEM': return '系统'
        default: return sender || '未知'
      }
    },
    formatTimestamp(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN')
    }
  }
}
</script>

<style scoped>
.chat-page {
  max-width: 1200px;
  margin: 0 auto;
}

.chat-page h1 {
  margin-top: 0;
  font-size: 2rem;
  margin-bottom: 1.5rem;
  color: #333;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 70vh;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #003366;
  color: white;
}

.connection-status {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
}

.connection-status.connected {
  background-color: #27ae60;
}

.connection-status.disconnected {
  background-color: #e74c3c;
}

.chat-messages {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  background-color: #f8f9fa;
}

.message {
  margin-bottom: 1rem;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.agent, .message.system {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 0.75rem;
  border-radius: 8px;
}

.message.user .message-content {
  background-color: #003366;
  color: white;
}

.message.agent .message-content, .message.system .message-content {
  background-color: white;
  border: 1px solid #ddd;
}

.sender {
  font-weight: bold;
  margin-bottom: 0.25rem;
  font-size: 0.9rem;
}

.content {
  margin-bottom: 0.25rem;
  line-height: 1.4;
}

.timestamp {
  font-size: 0.75rem;
  color: #999;
  text-align: right;
}

.chat-input {
  display: flex;
  padding: 1rem;
  background-color: white;
  border-top: 1px solid #ddd;
}

.chat-input input {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 0.5rem;
  font-size: 1rem;
}

.chat-input input:disabled {
  background-color: #f0f0f0;
}

.chat-input button {
  padding: 0.75rem 1.5rem;
  background-color: #003366;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>